<template>
  <!-- card -->
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <!-- form行内表单 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="注册时间">
          <!-- date picker带快捷选项 -->
          <el-date-picker
            v-model="dateArr"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadUsers">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- table带边框表格 -->
    <el-table :data="queryResult.records" border style="width: 100%">
      <el-table-column prop="id" label="用户ID" width="180" align="center" />
      <el-table-column
        prop="portrait"
        label="头像"
        v-slot="scope"
        align="center"
      >
        <!-- Avatar头像基本用法 -->
        <el-avatar :size="32" :src="scope.row.portrait"></el-avatar>
      </el-table-column>
      <el-table-column prop="name" label="用户名" align="center" />
      <el-table-column prop="phone" label="手机号" align="center" />
      <el-table-column prop="createTime" label="注册时间" align="center" />
      <el-table-column label="状态" align="center" v-slot="scope">
        <!-- 开关switch(扩展的 value 类型) -->
        <el-switch
          v-model="scope.row.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="ENABLE"
          inactive-value="DISABLE"
          active-text="启用"
          inactive-text="禁用"
          @change="handleChangeStatus(scope.row)"
        />
      </el-table-column>
      <el-table-column label="操作" align="center" v-slot="scope">
        <el-button @click="handleAllocRoleDlg(scope.row)">分配角色</el-button>
      </el-table-column>
    </el-table>
    <!-- Pagination 分页（完整功能） -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="queryResult.total"
    />
    <alloc-role-dlg ref="AllocRoleDlg" />
  </el-card>
</template>
<script>
import { queryUsers, enableUser, forbidUser } from "@/api/user";
import AllocRoleDlg from "./components/alloc-role.vue";
import dayjs from "dayjs";
export default {
  name: "UserIndex",
  data() {
    return {
      //查询条件
      queryParams: {
        currentPage: 1,
        pageSize: 10,
        phone: "",
        userId: undefined,
        startCreateTime: "",
        endCreateTime: "",
      },
      queryResult: {}, //查询结果
      //定义头像的默认值
      defaultFace:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      //date piker数据
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      //日期数据
      dateArr: [],
    };
  },
  //监听起始时间和结束时间
  watch: {
    dateArr: {
      deep: true,
      handler(newVal) {
        this.queryParams.startCreateTime = newVal[0];
        this.queryParams.endCreateTime = newVal[1];
      },
    },
  },
  created() {
    this.loadUsers();
  },
  methods: {
    //1加载用户信息
    loadUsers() {
      queryUsers(this.queryParams).then((res) => {
        if (res.data.code === "000000") {
          let {
            current: currentPage,
            pages,
            records,
            size: pageSize,
            total,
          } = res.data.data;
          Object.assign(this.queryParams, { currentPage, pageSize });
          //格式化时间dayjs
          records.forEach((user) => {
            //头像处理
            user.portrait = user.portrait || this.defaultFace;
            //格式化时间dayjs
            user.createTime = dayjs(user.createTime).format("YYYY-MM-DD");
          });
          this.queryResult = { pages, records, total };
        } else {
          this.$message.error("获取角色列表失败...");
        }
        console.log("获取角色管理列表信息1", res);
        console.log("获取角色管理列表信息records", this.queryResult.records);
      });
    },
    //2改变开启与禁用状态的方法
    handleChangeStatus(user) {
      const info = user.status === "ENABLE" ? "启用" : "禁用";
      //如果是enable就禁用,否则就启用
      (user.status === "ENABLE" ? enableUser(user.id) : forbidUser(user.id))
        .then(() => {
          this.$message.success(`${info}用户-操作成功!`);
        })
        .catch(() => {
          this.$message.error(`${info}用户-操作失败`);
        });
    },
    //改变页的大小
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageSize = val;
      this.loadUsers();
    },
    //当前页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.currentPage = val;
      this.loadUsers();
    },
    //（给用户）分配角色按钮事件
    handleAllocRoleDlg(user) {
      this.$refs.AllocRoleDlg.showAndInit(user);
    },
  },
  components: {
    AllocRoleDlg,
  },
};
</script>
<style lang="scss" scoped></style>
